<template>
    <div class="content flex-col">
        <div class="tenant-header flex-row">
            <div class="tenant-header-left">
                角色管理
            </div>
            <div class="tenant-header-right">
                <a-button type="primary" @click="handleAdd">
                    <a-icon type="plus" />
                    添加角色
                </a-button>
            </div>
        </div>
        <div class="tenant-content tenant-table">
            <el-table
                    :data="tableData"
                    row-class-name="category-table-tr"
                    height="100%"
                    style="width: 100%">
                <el-table-column
                        prop="roleName"
                        label="角色名称">
                </el-table-column>
                <el-table-column
                        prop="userSize"
                        label="用户数量">
                </el-table-column>
                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-button icon="el-icon-edit"
                                   v-if="isShowButton(scope.row.roleAlias)"
                                   @click="handleUpdate(scope.row)"
                                   type="text">编辑</el-button>
                        <el-button icon="el-icon-delete"
                                   v-if="isShowButton(scope.row.roleAlias)"
                                   @click="handleDelete(scope.row)"
                                   type="text" style="color: red">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog :title="submitState.state === 'add' ? '一 添加角色 一' : '一 修改角色 一'"
                   :visible.sync="dialogVisible"
                   center
                   @close="dialogVisible = false"
        >
            <el-form :model="form" :rules="formRules" ref="ruleForm" >
                <el-form-item label="角色名称：" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="form.roleName"></el-input>
                </el-form-item>
                <el-form-item label="功能权限：" :label-width="formLabelWidth">
                    <el-checkbox :indeterminate="form.isIndeterminate"
                                 v-model="form.checkAll"
                                 @change="handleCheckAllChange">全选</el-checkbox>
                    <div style="margin: 15px 0;"></div>
                    <el-checkbox-group v-model="form.roleAuthorities" @change="handleCheckedAuthorityChange">
                        <el-checkbox v-for="authority in form.authorities"
                                     :label="authority.ID"
                                     :key="authority.ID">
                            {{authority.Name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="formSubmit('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {getRoleList, addRole, deleteRole, editRole, getAuthorityList, getRoleByID} from '@/api/authority'

    export default {
        name: "role",
        data() {
            return {
                dialogVisible: false,
                submitState: {
                    state: 'add',
                    node: {}
                },
                page: {
                    total: 200,
                    size: 10,
                    current: 1
                },
                form: {
                    roleName: '',
                    authorities: [],
                    roleAuthorities: [],
                    checkAll: false,
                    isIndeterminate: true
                },
                formLabelWidth: '120px',
                formRules: {
                    roleName: [
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                        { min: 2, message: '长度大于 2 个字符', trigger: 'blur' }
                    ],
                },
                tableData: []
            }
        },
        methods:{
            getList() {
                getRoleList({
                    type: "BACK_ROLE"
                }).then((res) => {
                    if (res.data && res.data.code === 200) {
                        this.tableData = res.data.data;
                    }
                });

                getAuthorityList().then((res) => {
                    if (res.data && res.data.code === 200) {
                        this.form.authorities = res.data.data;
                    }
                })
            },
            isShowButton(roleAlias){
                if(!roleAlias){
                    return true;
                }
                return !roleAlias.includes('Administrator')
            },
            handleCheckAllChange(val) {
                let authorities = [];
                for (let i = 0; i < this.form.authorities.length; i++) {
                    authorities.push(this.form.authorities[i].ID);
                }
                this.form.roleAuthorities = val ? authorities : [];
                this.form.isIndeterminate = false;
            },
            handleCheckedAuthorityChange(value) {
                let checkedCount = value.length;
                this.form.checkAll = checkedCount === this.form.authorities.length;
                this.form.isIndeterminate = checkedCount > 0 && checkedCount < this.form.authorities.length;
            },
            formSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.dialogVisible = false;
                        if (this.submitState.state === "add") {
                            addRole({
                                "roleName": this.form.roleName,
                                "authorities": this.form.roleAuthorities,
                                "type": "BACK_ROLE"
                            }).then((res) => {
                                if (res.data && res.data.code === 200 && res.data.success) {
                                    this.$message.success("添加成功！")
                                    this.getList();
                                } else {
                                    this.$message.error("添加失败！")
                                }
                            })
                        }
                        else if (this.submitState.state === "update") {
                            let data = {
                                "id": this.submitState.node.id,
                                "roleName": this.form.roleName,
                                "authorities": this.form.roleAuthorities,
                                "type": "BACK_ROLE"
                            }
                            editRole(data).then((res) => {
                                if(res.data && res.data.success){
                                    this.$message.success("修改成功！")
                                    this.getList();
                                } else {
                                    this.$message.error("添加失败！")
                                }
                            })
                        }
                    } else {
                        return false;
                    }
                });
            },
            handleAdd() {
                this.form.roleName = "";
                this.form.roleAuthorities = [];
                this.form.checkAll = false;
                this.form.isIndeterminate = true;

                this.submitState.state = "add";
                this.dialogVisible = true;
            },
            handleUpdate(row) {

                this.form.roleName = row.roleName;
                this.submitState = {
                    state: "update",
                    node: row
                };

                getRoleByID({
                    id: row.id
                }).then((res) => {
                    if(res.data && res.data.success){
                        this.form.roleAuthorities = res.data.data.authorities || [];
                        this.form.checkAll = this.form.roleAuthorities.length === this.form.authorities.length;
                        this.dialogVisible = true;
                    }
                })
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {deleteRole({"id": row.id}).then((res) => {
                    if (res.data && res.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList();
                    }
                    else {
                        this.$message.error('删除失败!');
                    }
                })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
        },
        created() {
            this.getList();
        }
    }
</script>